<template>
  <el-dialog
    title="拍照上传"
    :visible.sync="visible"
    :before-close="onCancel"
    :modal="false"
    width="720px"
  >
    <div class="box" style="position: relative;">
      <video id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight" autoplay />
      <div v-if="loading" style="position: absolute;top: 50%;">
        <i class="el-icon-loading" />
        正在打开设备
      </div>
      <canvas id="canvasCamera" class="canvas" style="display: none;" :width="videoWidth*2" :height="videoHeight*2" />
    </div>
    <div slot="footer">
      <el-button
        icon="el-icon-camera"
        size="small"
        :loading="uploading"
        @click="drawImage"
      >
        拍照
      </el-button>
      <el-button
        icon="el-icon-circle-close"
        size="small"
        @click="onCancel"
      >
        取消
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { uploadQiNiu } from '@/api/common'

export default {
  name: 'TakePhotos',
  props: {
    visible: { type: Boolean, default: true },
    token: { type: String, default: '' },
    images: { type: Array, default: null }
  },
  data() {
    return {
      imgSrc: '',
      loading: false,
      uploading: false,
      open: false,
      thisCanvas: null,
      thisContext: null,
      thisVideo: null,
      videoWidth: 640,
      videoHeight: 360,
      streamTrack: null
    }
  },
  beforeDestroy() {
    this.stopNavigator()
  },
  mounted() {
    this.onTake()
  },
  methods: {
    onTake() {
      this.$nextTick(() => {
        this.getCompetence()
      })
    },
    onCancel() {
      if (!this.uploading) {
        this.resetCanvas()
        this.stopNavigator()
        this.$emit('on-cancel-modal', 'showCamera')
      }
    },
    getCompetence() {
      this.open = true
      this.thisCanvas = document.getElementById('canvasCamera')
      this.thisContext = this.thisCanvas.getContext('2d')
      this.thisVideo = document.getElementById('videoCamera')
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        this.loading = true
        navigator.mediaDevices.getUserMedia({
          // 不使用音频
          audio: false,
          // 定义宽高
          video: { width: 1280, height: 720 }
        }).then((stream) => {
          this.streamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()
          this.thisVideo.srcObject = stream
          this.thisVideo.onloadeddata = () => {
            this.thisVideo.play()
            this.loading = false
          }
        }).catch((err) => {
          this.loading = false
          console.log(err.name + ': ' + err.message)
          this.$message.error(err.message)
        })
      }
    },
    drawImage() {
      if (this.images.length >= 9) {
        this.$message.warning('最多只能上传9张图片'); return
      }
      this.thisContext.drawImage(this.thisVideo, 0, 0, 1280, 720)
      const base64 = this.thisCanvas.toDataURL('image/png')
      if (base64) {
        this.handleUploadImage(base64)
      } else {
        this.$message.warning('没有获取到有效的图片数据'); return
      }
    },
    handleUploadImage(base64 = null) {
      this.uploading = true
      uploadQiNiu(base64.split(',')[1], this.token).then(res => {
        this.$emit('camera', res.key)
      }).finally(() => {
        this.uploading = false
      })
    },
    resetCanvas() {
      this.imgSrc = ''
      const c = document.getElementById('canvasCamera')
      const cxt = c.getContext('2d')
      cxt.clearRect(0, 0, c.width, c.height)
    },
    stopNavigator() {
      if (this.streamTrack) {
        for (let i = 0; i < this.streamTrack.length; i++) {
          if (this.streamTrack[i].kind === 'audio' || this.streamTrack[i].kind === 'video') {
            this.streamTrack[i].stop()
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  display: flex;
  justify-content: center;
  align-content: center;
}
.canvas {
  border: 1px solid #e8e8e8;
}
</style>
